package cn.itcast.hotel.listener;

import cn.itcast.hotel.service.IHotelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author: itheima
 * @create: 2022-05-09 14:30
 */
@Component
@Slf4j
public class HotelListener {

    @Autowired
    private IHotelService hotelService;

    /**
     * 监听到消息后，完成ElasticSearch同步数据
     * @param msg
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    exchange = @Exchange(value = "hotel-exchange", durable = "true", type = ExchangeTypes.TOPIC),
                    value = @Queue(value = "hotel.insert.queue", durable = "true"),
                    key = {"#.insert"}
            )
    )
    public void handlerChangeMsg(String msg) {
        log.info("消费者监听到了修改消息，酒店ID{}", msg);
        try {
            hotelService.saveOrUpdateHotel(msg);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("修改索引库文档失败：{}",e.getMessage());
            throw new RuntimeException("更新失败");
        }
    }


    /**
     * 监听到消息后，完成ElasticSearch同步数据
     * @param msg
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    exchange = @Exchange(value = "hotel-exchange", durable = "true", type = ExchangeTypes.TOPIC),
                    value = @Queue(value = "hotel.delete.queue", durable = "true"),
                    key = {"#.delete"}
            )
    )
    public void handlerDeleteMsg(String msg) {
        log.info("消费者监听到了删除消息，酒店ID{}", msg);
        try {
            hotelService.deleteHotel(msg);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("删除索引库文档失败：{}",e.getMessage());
            throw new RuntimeException("删除失败");
        }
    }

}
